package msgtransfer

import (
	"context"

	"gitee.com/gao-deguang/easy-chat/apps/im/ws/websocket"
	"gitee.com/gao-deguang/easy-chat/apps/im/ws/ws"
	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/social"
	"gitee.com/gao-deguang/easy-chat/apps/task/mq/internal/svc"
	"gitee.com/gao-deguang/easy-chat/pkg/constant"
	"github.com/zeromicro/go-zero/core/logx"
)

type baseMsgTransfer struct {
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewbaseMsgTransfer(svc *svc.ServiceContext) *baseMsgTransfer {
	return &baseMsgTransfer{
		svcCtx: svc,
		Logger: logx.WithContext(context.Background()),
	}
}

func (m *baseMsgTransfer) Transfer(ctx context.Context, data *ws.Push) error {
	var err error
	switch data.ChatType {
	case constant.SingleChat:
		err = m.single(ctx, data)
	case constant.GroupChat:
		err = m.group(ctx, data)
	}
	return err
}

func (m *baseMsgTransfer) single(ctx context.Context, data *ws.Push) error {
	logx.Info("推送消息给wsClient推送消息给wsClient推送消息给wsClient推送消息给wsClient推送消息给wsClient")
	logx.Info("转发地址data.RecvServerAddr", data.RecvServerAddr)
	if wscli, ok := m.svcCtx.WsClients[data.RecvServerAddr]; ok {
		err := wscli.Send(websocket.Message{
			FrameType: websocket.FrameData,
			Method:    "push",
			FromId:    constant.SYSTEM_ROOT,
			Data:      data,
		})
		if err != nil {
			return err
		}
	} else {
		logx.Info("获取转发WsClient失败")
	}

	return nil
}

func (m *baseMsgTransfer) group(ctx context.Context, data *ws.Push) error {
	logx.Info("群聊群聊群聊推送消息给wsClient")
	users, err := m.svcCtx.Social.GroupUsers(ctx, &social.GroupUserReq{
		GroupId: data.RecvId,
	})

	if err != nil {
		return nil
	}

	data.RecvIds = make([]string, 0, len(users.List))

	for _, member := range users.List {
		if member.UserId == data.SendId {
			continue
		}

		data.RecvIds = append(data.RecvIds, member.UserId)
	}

	field := "server:discover.bandusers:"
	for _, rvid := range data.RecvIds {

		if data.RecvServerAddr, err = m.svcCtx.Redis.Hget(field, rvid); err != nil {
			logx.Info("接收者id和对应的错误：", rvid, err)
		}
		logx.Info("接收者接收者接收者接收者接收者GroupRecvIds:", data.RecvIds)
		logx.Info("地址地址地址：", data.RecvServerAddr)
		err = m.svcCtx.WsClients[data.RecvServerAddr].Send(websocket.Message{
			FrameType: websocket.FrameData,
			Method:    "push",
			FromId:    constant.SYSTEM_ROOT,
			Data:      data,
		})
		if err != nil {
			return err
		}

	}

	return nil

}
